package me.goldze.mvvmhabit.base;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.view.WindowCompat;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProviders;

import com.afollestad.materialdialogs.MaterialDialog;
import com.gyf.immersionbar.ImmersionBar;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;

import me.goldze.mvvmhabit.R;
import me.goldze.mvvmhabit.base.BaseViewModel.ParameterField;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.lks.router.RouteHelper;
import me.goldze.mvvmhabit.utils.NoDoubleClickListener;
import me.goldze.mvvmhabit.widget.CommonTitleView;
import me.goldze.mvvmhabit.widget.dialog.BaseNiceDialog;
import me.goldze.mvvmhabit.widget.dialog.NiceDialog;
import me.goldze.mvvmhabit.widget.dialog.ViewConvertListener;
import me.goldze.mvvmhabit.widget.dialog.ViewHolder;
import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.Utils;
import me.imid.swipebacklayout.lib.app.SwipeBackActivityBase;
import me.imid.swipebacklayout.lib.app.SwipeBackActivityHelper;


/**
 * Created by goldze on 2017/6/15.
 * 一个拥有DataBinding框架的基Activity
 * 这里根据项目业务可以换成你自己熟悉的BaseActivity, 但是需要继承RxAppCompatActivity,方便LifecycleProvider管理生命周期
 */
public abstract class BaseActivity<V extends ViewDataBinding, VM extends BaseViewModel> extends RxAppCompatActivity implements SwipeBackActivityBase, IBaseView {
    protected V binding;
    protected VM viewModel;
    private int viewModelId;
    private KProgressHUD mKProgressHUD;
    CommonTitleView titleView;
    private SwipeBackActivityHelper mHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        super.onCreate(savedInstanceState);
        //页面接受的参数方法
        try {
            mHelper = new SwipeBackActivityHelper(this);
            mHelper.onActivityCreate();
            mKProgressHUD = KProgressHUD.create(this).setStyle(KProgressHUD.Style.SPIN_INDETERMINATE).setCancellable(true).setLabel("正在载入").setAnimationSpeed(2).setDimAmount(0.5f);
            mKProgressHUD.setCancellable(true);
            initParam();
            //私有的初始化Databinding和ViewModel方法
            initViewDataBinding(savedInstanceState);
            //私有的ViewModel与View的契约事件回调逻辑
            registorUIChangeLiveDataCallBack();
//            setBarColor(this.getResources().getColor(R.color.main_bg));
            //页面数据初始化方法
            if (commonBarColor()) {
                ImmersionBar.with(this).fitsSystemWindows(true).keyboardEnable(true).statusBarColor(R.color.white)
                        .statusBarDarkFont(true, 1f).init();
            }
            initData();
            //页面事件监听的方法，一般用于ViewModel层转到View层的事件注册
            initViewObservable();
            //注册RxBus
            viewModel.registerRxBus();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public boolean commonBarColor() {
        return true;
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mHelper.onPostCreate();
    }

    @Override
    public Resources getResources() {
        // 字体大小不跟随系统
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    @Override
    public View findViewById(int id) {
        View v = super.findViewById(id);
        if (v == null && mHelper != null)
            return mHelper.findViewById(id);
        return v;
    }

    @Override
    public SwipeBackLayout getSwipeBackLayout() {
        return mHelper.getSwipeBackLayout();
    }

    @Override
    public void setSwipeBackEnable(boolean enable) {
        getSwipeBackLayout().setEnableGesture(enable);
    }

    @Override
    public void scrollToFinishActivity() {
        Utils.convertActivityToTranslucent(this);
        getSwipeBackLayout().scrollToFinishActivity();
    }

    public void setBarColor(int color) {
        Window window = getWindow();
        window.clearFlags(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        //设置状态栏颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.setStatusBarColor(color);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除Messenger注册
        Messenger.getDefault().unregister(viewModel);
        if (viewModel != null) {
            viewModel.removeRxBus();
        }
        if (binding != null) {
            binding.unbind();
        }
    }

    /**
     * 获取标题栏布局.
     */
    public CommonTitleView getTitleBar() {
        titleView.setVisibility(View.VISIBLE);
        titleView.setBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        return titleView;
    }

    /**
     * 注入绑定
     */
    private void initViewDataBinding(Bundle savedInstanceState) {
        //DataBindingUtil类需要在project的build中配置 dataBinding {enabled true }, 同步后会自动关联android.databinding包
        LayoutInflater mInflater = LayoutInflater.from(this);
        ViewGroup mRootView = (ViewGroup) View.inflate(this, R.layout.base_layout_titlebar, null);
        titleView = mRootView.findViewById(R.id.ctBaseTitle);
        FrameLayout frameLayout = mRootView.findViewById(R.id.flBaseContent);
        super.setContentView(mRootView);
        binding = DataBindingUtil
                .inflate(mInflater, initContentView(savedInstanceState), frameLayout, true);
//        binding = DataBindingUtil.setContentView(this, initContentView(savedInstanceState));
        viewModelId = initVariableId();
        viewModel = initViewModel();
        if (viewModel == null) {
            Class modelClass;
            Type type = getClass().getGenericSuperclass();
            if (type instanceof ParameterizedType) {
                modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[1];
            } else {
                //如果没有指定泛型参数，则默认使用BaseViewModel
                modelClass = BaseViewModel.class;
            }
            viewModel = (VM) createViewModel(this, modelClass);
        }
        //关联ViewModel
        binding.setVariable(viewModelId, viewModel);
        //支持LiveData绑定xml，数据改变，UI自动会更新
        binding.setLifecycleOwner(this);
        //让ViewModel拥有View的生命周期感应
        getLifecycle().addObserver(viewModel);
        //注入RxLifecycle生命周期
        viewModel.injectLifecycleProvider(this);
    }

    //刷新布局
    public void refreshLayout() {
        if (viewModel != null) {
            binding.setVariable(viewModelId, viewModel);
        }
    }

    /**
     * 设置状态栏透明
     */
    public void setTranslucentStatus() {

        Window window = getWindow();
        if (null == window) {
            return;
        }
        // 5.0以上系统状态栏透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    public int getStatusBarHeight(Context context) {
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }

    /**
     * =====================================================================
     **/
    //注册ViewModel与View的契约UI回调事件
    protected void registorUIChangeLiveDataCallBack() {
        //加载对话框显示
        viewModel.getUC().getShowDialogEvent().observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String title) {
                showDialog(title, true);
            }
        });
        viewModel.getUC().getShowDismissNoDialogEvent().observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String title) {
                showDialog(title, false);
            }
        });
        //加载对话框消失
        viewModel.getUC().getDismissDialogEvent().observe(this, new Observer<Void>() {
            @Override
            public void onChanged(@Nullable Void v) {
                dismissDialog();
            }
        });
        //打开网页
        viewModel.getUC().getStartWebEvent().observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                Intent intent = new Intent();
                intent.setData(Uri.parse(s));
                intent.setAction(Intent.ACTION_VIEW);
                startActivity(intent);
            }
        });
        //跳入新页面
        viewModel.getUC().getStartActivityEvent().observe(this, new Observer<Map<String, Object>>() {
            @Override
            public void onChanged(@Nullable Map<String, Object> params) {
                Class<?> clz = (Class<?>) params.get(ParameterField.CLASS);
                Bundle bundle = (Bundle) params.get(ParameterField.BUNDLE);
                startActivity(clz, bundle);
            }
        });
        viewModel.getUC().getStartActivityForResultEvent().observe(this, new Observer<Map<String, Object>>() {
            @Override
            public void onChanged(@Nullable Map<String, Object> params) {
                Class<?> clz = (Class<?>) params.get(ParameterField.CLASS);
                Bundle bundle = (Bundle) params.get(ParameterField.BUNDLE);
                startActivityForResult(clz, bundle);
            }
        });
        //跳入ContainerActivity
        viewModel.getUC().getStartContainerActivityEvent().observe(this, new Observer<Map<String, Object>>() {
            @Override
            public void onChanged(@Nullable Map<String, Object> params) {
                String canonicalName = (String) params.get(ParameterField.CANONICAL_NAME);
                Bundle bundle = (Bundle) params.get(ParameterField.BUNDLE);
                startContainerActivity(canonicalName, bundle);
            }
        });
        //跳入新页面
        viewModel.getUC().getStartModuleActivityEvent().observe(this, new Observer<Map<String, Object>>() {
            @Override
            public void onChanged(@Nullable Map<String, Object> params) {
                String key = (String) params.get(ParameterField.ROUTER_KEY);
                int requestCode = 0;
                if (params.containsKey(ParameterField.ROUTER_REQUEST_CODE)) {
                    requestCode = (int) params.get(ParameterField.ROUTER_REQUEST_CODE);
                }
                Bundle bundle = (Bundle) params.get(ParameterField.BUNDLE);


                Intent intent = new Intent();
                intent.putExtra(RouteHelper.ROUTE_KEY, key);
                if (null != bundle) {
                    intent.putExtras(bundle);
                }

                startModuleActivity(intent, requestCode);

            }
        });
        //关闭界面
        viewModel.getUC().getFinishEvent().observe(this, new Observer<Void>() {
            @Override
            public void onChanged(@Nullable Void v) {
                finish();
            }
        });
        //关闭界面
        viewModel.getUC().getFinishOkEvent().observe(this, new Observer<Map<String, Object>>() {
            @Override
            public void onChanged(@Nullable Map<String, Object> params) {
                Intent data = new Intent();
                if (null != params) {

                    Bundle bundle = (Bundle) params.get(ParameterField.BUNDLE);
                    if (bundle != null) {
                        data.putExtras(bundle);
                    }
                }
                setResult(RESULT_OK, data);
                finish();
            }
        });
        //关闭上一层
        viewModel.getUC().getOnBackPressedEvent().observe(this, new Observer<Void>() {
            @Override
            public void onChanged(@Nullable Void v) {
                onBackPressed();
            }
        });
    }

    public void showDialog(String title, boolean isClickCancel) {
        if (null == mKProgressHUD) {
            return;
        }
        mKProgressHUD.setLabel(title).setCancellable(isClickCancel).show();
    }

    public void showDialog() {
        if (null == mKProgressHUD) {
            return;
        }
        mKProgressHUD.setLabel("正在载入").show();
    }

    public void dismissDialog() {
//        IosDialogStyleUtils.getInstance().dissmissIosDialog();
        if (null == mKProgressHUD) {
            return;
        }
        mKProgressHUD.dismiss();
    }

    //    TODO====
    public void showAuthDialog() {
        NiceDialog.init().setLayoutId(R.layout.dialog_confirm_setting)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        Button tvDone = holder.getView(R.id.tvDone);
                        TextView tvContent = holder.getView(R.id.tvContent);
                        TextView tvTitle = holder.getView(R.id.tvTitle);
                        TextView tvCancel = holder.getView(R.id.tvCancel);
                        tvTitle.setText("提示");
                        tvContent.setText("您还没有实名认证，请认证后操作");
                        tvCancel.setText("暂不认证");
                        tvDone.setText("立即认证");
                        tvCancel.setOnClickListener(new NoDoubleClickListener() {
                            @Override
                            protected void onNoDoubleClick(View v) {
                                dialog.dismiss();
                            }
                        });
                        tvDone.setOnClickListener(new NoDoubleClickListener() {
                            @Override
                            protected void onNoDoubleClick(View v) {
                                try {
//                                    Class ca = Class.forName("com.cn.user.ui.user_authentication.ActUserAuthentication");
//                                    Context context = AppManager.getAppManager().currentActivity();
//                                    Intent intent = new Intent(context, ca);
//                                    context.startActivity(intent);
                                    Intent intent = new Intent();
                                    intent.putExtra(RouteHelper.ROUTE_KEY, "user_ActUserAuthentication");
                                    startModuleActivity(intent,0);
                                } catch (Exception er) {
                                    er.printStackTrace();
                                }
                                dialog.dismiss();
                            }
                        });
                    }
                })
                .setWidth(300).show(getSupportFragmentManager());
    }

    /**
     * 跳转页面
     *
     * @param clz 所跳转的目的Activity类
     */
    public void startActivity(Class<?> clz) {
        startActivity(new Intent(this, clz));
    }

    /**
     * 跳转页面
     *
     * @param clz    所跳转的目的Activity类
     * @param bundle 跳转所携带的信息
     */
    public void startActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    public void startActivityForResult(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent(this, clz);
        int requestCode = 0;
        if (bundle != null) {
            intent.putExtras(bundle);
            requestCode = bundle.getInt(ParameterField.REQUEST_CODE);
        }
        intent.putExtra(ParameterField.REQUEST_CODE, requestCode);
        startActivityForResult(intent, requestCode);
    }

    public void startModuleActivity(Intent intent, int requestCode) {
        RouteHelper.openActivity(intent, this, requestCode);
    }

    /**
     * 跳转容器页面
     *
     * @param canonicalName 规范名 : Fragment.class.getCanonicalName()
     */
    public void startContainerActivity(String canonicalName) {
        startContainerActivity(canonicalName, null);
    }

    /**
     * 跳转容器页面
     *
     * @param canonicalName 规范名 : Fragment.class.getCanonicalName()
     * @param bundle        跳转所携带的信息
     */
    public void startContainerActivity(String canonicalName, Bundle bundle) {
        Intent intent = new Intent(this, ContainerActivity.class);
        intent.putExtra(ContainerActivity.FRAGMENT, canonicalName);
        if (bundle != null) {
            intent.putExtra(ContainerActivity.BUNDLE, bundle);
        }
        startActivity(intent);
    }

    /**
     * =====================================================================
     **/
    @Override
    public void initParam() {

    }

    /**
     * 初始化根布局
     *
     * @return 布局layout的id
     */
    public abstract int initContentView(Bundle savedInstanceState);

    /**
     * 初始化ViewModel的id
     *
     * @return BR的id
     */
    public abstract int initVariableId();

    /**
     * 初始化ViewModel
     *
     * @return 继承BaseViewModel的ViewModel
     */
    public VM initViewModel() {
        return null;
    }

    @Override
    public void initData() {

    }

    @Override
    public void initViewObservable() {

    }

    /**
     * 创建ViewModel
     *
     * @param cls
     * @param <T>
     * @return
     */
    public <T extends ViewModel> T createViewModel(FragmentActivity activity, Class<T> cls) {
        return ViewModelProviders.of(activity).get(cls);
    }
}
